<template>
  <!-- 区域 -->
  <div>
    <div class="app-page">
      <org-tree
        title="组织机构"
        :tree-data="treeData"
        :mouse-button="false"
        :loading="$loadingPlugin.getTreeData"
        class="content"
        @currentChange="currentChange"
        @asideVisibleChange="asideVisible = !asideVisible"
      />
      <div class="right">
        <el-table-form ref="form" :model="query">
          <el-form-item class="merge-item">
            <el-select v-model="qtype" style="width: 170px; margin-right: 2px;">
              <el-option value="csmRgPhone" label="电话" />
              <el-option value="csmCode" label="客户编号" />
              <el-option value="csmName" label="客户名称" />
              <el-option value="csmAddress" label="地址" />
              <el-option value="sfzh" label="身份证号" />
            </el-select>
            <el-input v-model.trim="txt" placeholder="请输入" clearable />
          </el-form-item>
          <el-form-item label="优惠权益:" prop="preferentialPackageId">
            <el-select v-model="query.preferentialPackageId" clearable>
              <el-option
                v-for="item in preferentialList"
                :key="item.preferentialPackageId"
                :label="item.preferentialPackageName"
                :value="item.preferentialPackageId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态:" prop="status">
            <el-select v-model="query.status" clearable>
              <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <template v-slot:btns>
            <el-button v-permission="[10020402,1]" type="primary" icon="el-icon-search" @click="search">查询</el-button>
          </template>
        </el-table-form>
        <div style="margin-bottom: 10px;" class="btn-group">
          <div>
            <el-button v-permission="[10020402,2]" type="primary" style="margin-right: 5px;" icon="el-icon-plus" @click="handleAdd">新增</el-button>
            <el-button v-permission="[10020402,3]" type="primary" style="margin-right: 5px;" icon="el-icon-edit" @click="handleEdits">修改权益</el-button>
            <el-button v-permission="[10020402,4]" type="primary" style="margin-right: 5px;" icon="el-icon-tickets" @click="handleAudits">审核</el-button>
            <el-button v-permission="[10020402,5]" type="primary" style="margin-right: 5px;" icon="el-icon-delete" @click="handleDeletes">删除</el-button>
          </div>
        </div>
        <lb-table
          ref="lbTable"
          v-el-height-adaptive-table="{bottomOffset:10}"
          class="searchTable"
          border
          highlight-current-row
          element-loading-text="加载中"
          :column="tableData.column"
          :data="tableData.data"
          pagination
          :total="tableData.total"
          custom-column
          :immediate-fetch="false"
          @fetch="fetchData"
          @selection-change="handleSelectionChange"
        />
      </div>
    </div>
    <add-client ref="addClient" @refresh="search" />
    <el-dialog
      v-el-drag-dialog
      title="修改权益"
      :visible.sync="visible"
      width="300px"
    >
      <div class="dialog-content">
        <span class="label">优惠权益：</span>
        <el-select v-model="dialog.preferentialPackageId">
          <el-option
            v-for="item in preferentialList"
            :key="item.preferentialPackageId"
            :label="item.preferentialPackageName"
            :value="item.preferentialPackageId"
          />
        </el-select>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="visible = false">
          关闭
        </el-button>
        <el-button type="primary" @click="handleSave">
          保存
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    organizationQueryList,
    preferentialSelect,
    customerPreferential,
    customerPreferentialEdit,
    customerPreferentialAudit,
    customerPreferentialDelete
  } from '@/api'
  import { formatColumnMap, parseTime } from '@/utils'
  import getTreeData from '@/utils/jsonTree'
  import OrgTree from '@/views/components/OrgTree'
  import AddClient from './addClient.vue'

  export default {
    name: 'clientTab',
    components: {
      OrgTree, AddClient
    },
    data() {
      return {
        indexId: 0,
        treeData: [],
        currentOrg: null,
        selectLine: null,
        asideVisible: false,
        qtype: 'csmRgPhone',
        txt: '',
        query: {
          preferentialPackageId: '',
          status: ''
        },
        preferentialList: [],
        multipleSelection: [],
        statusOptions: [
          {
            label: '待审核',
            value: 1
          },
          {
            label: '已审核',
            value: 2
          }
        ],
        tableData: {
          total: 0,
          column: [
            {
              type: 'selection'
            },
            {
              prop: 'csmCode',
              width: 100,
              label: '客户编号'
            },
            {
              prop: 'csmName',
              width: 100,
              label: '客户名称'
            },
            {
              prop: 'csmRgPhone',
              width: 100,
              label: '电话'
            },
            {
              prop: 'csmAddress',
              width: 150,
              label: '地址'
            },
            {
              prop: 'sfzh',
              width: 120,
              label: '身份证'
            },
            {
              prop: 'orgName',
              width: 120,
              label: '所属机构'
            },
            {
              prop: 'preferentialPackageName',
              width: 100,
              label: '优惠权益',
              render: (h, { row }) => (
                <span>{row.preferentialPackageId && formatColumnMap(this.preferentialList, 'preferentialPackageId', row.preferentialPackageId, 'preferentialPackageName')}</span>
              )
            },
            {
              prop: 'status',
              width: 100,
              label: '状态',
              render: (h, { row }) => (
                <span>{row.status && formatColumnMap(this.statusOptions, 'value', row.status, 'label')}</span>
              )
            },
            {
              prop: 'modifyUser',
              width: 100,
              label: '最后修改人'
            },
            {
              prop: 'modifyTime',
              width: 160,
              label: '最后修改时间',
              render: (h, { row }) => (
                <span>
                {row.modifyTime && parseTime(row.modifyTime, '{y}-{m}-{d} {h}:{i}')}
                </span>
              )
            },
            {
              prop: 'auditor',
              width: 100,
              label: '审核人'
            },
            {
              prop: 'auditTime',
              width: 160,
              label: '审核时间',
              render: (h, { row }) => (
                <span>
                {row.auditTime && parseTime(row.auditTime, '{y}-{m}-{d} {h}:{i}')}
                </span>
              )
            },
            {
              label: '操作',
              width: 90,
              fixed: 'right',
              render: (h, { row, $index }) => {
                return (
                <div>
                  <el-dropdown>
                    <span class='el-dropdown-link'>
                      更多<i class='el-icon-arrow-down el-icon--right'></i>
                    </span>
                    <el-dropdown-menu slot='dropdown'>
                      <el-dropdown-item v-permission={[10020402, 3]}>
                        <el-link size='mini' underline={false} onClick={() => this.handleEdit(row)}>
                            修改权益
                        </el-link>
                      </el-dropdown-item>
                      {row.status === 1 && (<el-dropdown-item v-permission={[10020402, 4]}>
                        <el-link size='mini' underline={false} onClick={() => this.handleAudit(row)}>
                            审核
                        </el-link>
                      </el-dropdown-item>)}
                      {row.status === 1 && (<el-dropdown-item v-permission={[10020402, 5]}>
                        <el-link size='mini' underline={false} onClick={() => this.handleDelete(row)}>
                            删除
                        </el-link>
                       </el-dropdown-item>)}
                    </el-dropdown-menu>
                  </el-dropdown>
                </div>)
              }
            }
          ],
          data: []
        },
        visible: false,
        dialog: {
          preferentialPackageId: ''
        }
      }
    },
    created() {
      this.getTreeData()
      this.preferentialSelect()
    },
    methods: {
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      // 列表查询
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        query[this.qtype] = this.txt
        query.orgSNNo = this.currentOrg.orgSNNo
        const res = await customerPreferential(query)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
      },
      // 获取组织机构数据
      async getTreeData() {
        const res = await organizationQueryList({})
        const data = res.data.map(item => ({
          label: item.orgName,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 获取权益列表
      async preferentialSelect() {
        const params = {
          currentPage: 1,
          pageSize: 9999
        }
        const res = await preferentialSelect(params)
        this.preferentialList = res.data.rows
        this.preferentialList = this.preferentialList.filter(item => item.preferentialPackageStatus === 2)
      },
      // 选择组织机构变化
      currentChange(current) {
        this.currentOrg = current
        if (this.currentOrg) this.$refs.lbTable.fetch()
      },
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      handleAdd() {
        this.$refs.addClient.open()
      },
      // 修改
      handleEdit(row) {
        this.visible = true
        this.dialog.preferentialPackageId = ''
        this.currentRow = row
        this.type = 'single'
      },
      // 修改保存
      handleSave() {
        if (!this.dialog.preferentialPackageId) {
          this.$message.warning('请选择优惠权益')
          return
        }
        let paramsArr = []
        if (this.type === 'single') {
          paramsArr.push(this.currentRow)
          paramsArr[0].newPreferentialPackageId = this.dialog.preferentialPackageId
          paramsArr[0].newPreferentialPackageName = formatColumnMap(this.preferentialList, 'preferentialPackageId', this.dialog.preferentialPackageId, 'preferentialPackageName')
        } else {
          paramsArr = this.multipleSelection
          paramsArr.forEach((item) => {
            item.newPreferentialPackageId = this.dialog.preferentialPackageId
            item.newPreferentialPackageName = formatColumnMap(this.preferentialList, 'preferentialPackageId', this.dialog.preferentialPackageId, 'preferentialPackageName')
          })
        }
        customerPreferentialEdit(paramsArr).then(res => {
          console.log(res)
          if (res.data) {
            this.visible = false
            this.$message.success('保存成功')
            this.search()
          }
        })
      },
      // 审核
      handleAudit(row) {
        customerPreferentialAudit([row]).then(res => {
          if (res.data) {
            this.$message.success('审核成功')
            this.search()
          }
        })
      },
      // 删除
      handleDelete(row) {
        this.$confirm('确认要删除该优惠客户吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          customerPreferentialDelete([row]).then(res => {
            this.$message.success('删除成功')
            this.search()
          })
        }).catch(() => {})
      },
      // 批量修改
      handleEdits() {
        if (this.multipleSelection.length === 0) {
          this.$message.warning('请先勾选客户')
          return
        }
        this.visible = true
        this.dialog.preferentialPackageId = ''
        this.type = 'batch'
      },
      // 批量审核
      handleAudits() {
        if (this.multipleSelection.length === 0) {
          this.$message.warning('请先勾选客户')
          return
        }
        const auditedArr = []
        this.multipleSelection.forEach((item) => {
          if (item.status === 2) {
            auditedArr.push('客户地址:' + item.csmName + ',客户地址:' + item.csmAddress)
          }
        })
        if (auditedArr.length > 0) {
          this.$message.warning(auditedArr.join(',') + '已审核')
          return
        }
        customerPreferentialAudit(this.multipleSelection).then(res => {
          if (res.data) {
            this.$message.success('审核成功')
            this.search()
          }
        })
      },
      // 批量删除
      handleDeletes() {
        if (this.multipleSelection.length === 0) {
          this.$message.warning('请先勾选客户')
          return
        }
        const auditedArr = []
        this.multipleSelection.forEach((item) => {
          if (item.status === 2) {
            auditedArr.push('客户地址:' + item.csmName + ',客户地址:' + item.csmAddress)
          }
        })
        if (auditedArr.length > 0) {
          this.$message.warning(auditedArr.join(',') + '已审核')
          return
        }
        this.$confirm('确认要删除该优惠客户吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          customerPreferentialDelete(this.multipleSelection).then(res => {
            this.$message.success('删除成功')
            this.search()
          })
        }).catch(() => {})
      }
    }
  }
</script>

<style lang="scss" scoped>
.app-page {
  display: flex;
  width: 100%;
  height: calc(100vh - 180px);
  padding: 0;
  .content {
    max-width: 280px;
    padding: 0 10px 0 10px;
  }
}
.dialog-content {
  display: flex;
  .label {
    width: 100px;
    line-height: 30px;
  }
}

.right {
  flex: 1;
  padding-left: 8px;
  overflow-y: auto;
}
</style>
